import router from '@/router'
import Axios from 'axios'
import store from '@/store'

const https=Axios.create()
//https.defaults.headers.common['Authorization'] = store.state.token;
https.interceptors.request.use(config =>{
	/*if(store.state.token){*/
	if(localStorage.getItem("token")){
		console.log(localStorage.getItem("token"))
		config.headers.common['Authorization']=localStorage.getItem("token")
	}
	return config;
},error=>{
	return Promise.reject(error)
});
https.interceptors.response.use(response=>{
	if(response.data){
		let data=response.data;
		//console.log(data)
		switch(data.code){
			case '44004':
			store.commit('del_token');
			localStorage.removeItem("openid");//清除openid
        //微信登录逻辑
        let ua = window.navigator.userAgent.toLowerCase();
        let isweiChat = ua.match(/MicroMessenger/i) == 'micromessenger';
        // alert(isweiChat)
        //是否微信登录
        if (!isweiChat) {
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
        }
        else{
          window.location.reload();
        }

		}
	}
	return response;
},error =>{
	if(error.response){
		switch(error.response.code){
			case '401':
			case '302':
			store.commit('del_token');
			localStorage.removeItem("openid");//清除openid
        //微信登录逻辑
        let ua = window.navigator.userAgent.toLowerCase();
        let isweiChat = ua.match(/MicroMessenger/i) == 'micromessenger';
        if (!isweiChat) {
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
        } else{
          window.location.reload();
        }
		}
	}
	return Promise.reject(error)
}
)
export default https
